import {postReqLog,getReq} from "../http";
import {formatTime} from "../tool";

const ORDER_LIST = 'ORDER_LIST'
const ERROR_MSG = 'ERROR_MSG'

const initState={
   data:{
       list:[],
       data:{}
   },
   msg:null
}
// reducer
export function order(state=initState, action){
    switch(action.type){
        case ORDER_LIST:
            return {...state,data:action.payload}
        case ERROR_MSG:
            return {...state,msg:action.msg}
        default:
            return state
    }
}

function success(obj){


    return {type: ORDER_LIST, payload:obj}
}

function errorMsg(msg){
    return { msg, type:ERROR_MSG }
}


export function getOrderList(data){
    return async dispatch=>{
        let res = await getReq('/api/order/list',data)
        if(res.data){
            dispatch(getUserList(res.data))
        }else {
            dispatch(errorMsg(res.msg))
        }
    }
}

function getUserList(data) {
    let newList = []
    for(let i = 0; i < data.list.length; i++){
        let item = data.list[i]
        newList.push({...item,key:i+1,createTime:formatTime(new Date(item.createTime)),payment:`￥${item.payment}`})

    }
    return {type:ORDER_LIST,payload:{...data, list:newList,current:1}}
}
function orderDetailSuccess(data) {
    let newList = []
    for(let i = 0; i < data.orderItemVoList.length; i++){
        let item = data.orderItemVoList[i]
        newList.push({...item,key:i+1,createTime:formatTime(new Date(item.createTime)),
            totalPrice:`￥${item.totalPrice}`,
            currentUnitPrice:`￥${item.currentUnitPrice}`
        })

    }
    return {type:ORDER_LIST,payload:{...data, orderItemVoList:newList,current:1}}
}
export function orderDetail(orderNo) {
    return async dispatch=>{
        let res = await getReq('/api/order/detail',{orderNo})
        if(res.data){
            dispatch(orderDetailSuccess(res.data))
        }
    }
}



